package com.zz.tijian.async.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zz.tijian.async.AsyncReportService;
import com.zz.tijian.entity.*;
import com.zz.tijian.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AsyncReportServiceImpl implements AsyncReportService {

    @Autowired
    private SetmealdetailedService setmealdetailedService;
    @Autowired
    private CheckitemService checkitemService;
    @Autowired
    private CheckitemdetailedService checkitemdetailedService;
    @Autowired
    private CireportService cireportService;
    @Autowired
    private CidetailedreportService cidetailedreportService;

    // 插入套餐报告
    @Transactional
    public void insertPackageReports(Orders orders) {
        try {
            LambdaQueryWrapper<Setmealdetailed> setmealdetailedWrapper = new LambdaQueryWrapper<>();
            setmealdetailedWrapper.eq(Setmealdetailed::getSmId, orders.getSmId());
            List<Setmealdetailed> setmealList = setmealdetailedService.list(setmealdetailedWrapper);

            for (Setmealdetailed setmeal : setmealList) {
                Checkitem checkitem = checkitemService.getById(setmeal.getCiId());

                Cireport cireport = new Cireport();
                cireport.setOrderId(orders.getOrderId());
                cireport.setCiId(setmeal.getCiId());
                cireport.setCiName(checkitem.getCiName());
                cireportService.save(cireport);

                LambdaQueryWrapper<Checkitemdetailed> checkitemdetailedWrapper = new LambdaQueryWrapper<>();
                checkitemdetailedWrapper.eq(Checkitemdetailed::getCiId, setmeal.getCiId());
                List<Checkitemdetailed> checkitemdetailedList = checkitemdetailedService.list(checkitemdetailedWrapper);

                for (Checkitemdetailed detail : checkitemdetailedList) {
                    Cidetailedreport cidetailedreport = new Cidetailedreport();
                    BeanUtils.copyProperties(detail, cidetailedreport);
                    cidetailedreport.setOrderId(orders.getOrderId());
                    cidetailedreportService.save(cidetailedreport);
                }
            }
        } catch (Exception e) {
            log.error("插入报告失败", e);
            throw e; // Ensure transaction rollback
        }
    }

    @Async("asyncServiceExecutor")
    @Override
    public void executeAsync(Orders orders) {
        try {
            insertPackageReports(orders);
        } catch (Exception e) {
            log.error("异步插入报告失败", e);
            throw e;
        }
    }
}
